/*
 * Amkai Enterprise Solution (AES.) 
 * Copyright 2004 by Amkai(TM), Inc.
 * www.amkai.com
 * 
 * Project: webservice
 * Package: com.amkai.aes.webservice.binary.objecthandler
 * File: RADBeanSaveHandler.java
 * Created: Apr 14, 2006 5:48:14 PM
 * Author: johnny 
 * 
 */
package com.amkai.aes.webservice.binary.objecthandler;

import java.beans.PropertyDescriptor;

import org.homedns.mpetmaya.tools.LangUtil;

import com.amkai.aes.aescommon.service.binary.job.RADBeanSaveJob;
import com.amkai.aes.aescommon.service.result.RADBeanSaveResult;
import com.amkai.aes.generatedbeans.dictionary.Item;
import com.amkai.aes.server.dictionary.DictionarySchedulingResourceManager;
import com.amkai.aes.server.dictionary.SharedDictionaryManager;
import com.amkai.aes.server.domaincommiter.dictionaryeditor.StateCodesCommiter;
import com.amkai.aes.webservice.binary.JobObjectHandler;
import com.amkai.common.base.utils.BeanManager;
import com.amkai.common.extensions.hibernate.config.SiteManager;
import com.amkai.common.extensions.hibernate.config.manager.SessionManager;
import com.amkai.rad.designerbase.beans.ChangedKind;
import com.amkai.rad.designerbase.beans.RADBean;

/**
 * RADBeanSaveHandler
 * @author johnny
 * Description:
 *
 */
public class RADBeanSaveHandler implements JobObjectHandler<RADBeanSaveJob, RADBean, RADBeanSaveResult> {

	public RADBeanSaveResult process(RADBeanSaveJob job, RADBean object) throws Exception {
		SessionManager sm = SiteManager.Start();
		SharedDictionaryManager sdm = new SharedDictionaryManager(sm);
		RADBeanSaveResult result = new RADBeanSaveResult();
		try {
			sm.openTransaction();
			if (object.getChangedKind() == ChangedKind.DELETED) {
				PropertyDescriptor pd = BeanManager.getType(object.getClass(), "id");
				Long id = (Long) pd.getReadMethod().invoke(object);
				object = sm.get(object.getClass(), id);
				object.setChangedKind(ChangedKind.DELETED);
			} 
	
			Item item=LangUtil.as(Item.class, object);
			// KKORNEL: AES-4131 : Updating Item
			// KKORNEL: AES-11533
			if (item==null) {
				sm.saveRAD(object);			
			} else {
				sdm.saveItem(item);				
				// KKORNEL: AES-5778
				StateCodesCommiter.commitItemStateCodes(sm, item);
			}
			DictionarySchedulingResourceManager.executeSchedulingResourceUpdate(object, sm);
			sm.commitTransaction();
			result.setSuccess(true);
			result.setKind(object.getChangedKind());
			
			PropertyDescriptor pd = BeanManager.getType(object.getClass(), "id");
			Long id = (Long) pd.getReadMethod().invoke(object);
			result.setId(id);
			
		} catch (Exception e) {
			sm.rollbackTransaction();
			throw e;
		}
		finally {
			sm.closeSession();
		}
		return result;
	}

}
